<template>
  <a-layout style="min-height: 100vh; background: #f5f7fa;">
    <nav-bar />
    
    <a-layout-content style="padding: 30px 50px; max-width: 1600px; margin: 0 auto; width: 100%;">
      <!-- 页面标题 -->
      <div style="text-align: center; margin-bottom: 24px;">
        <h1 style="font-size: 28px; color: #2c3e50; font-weight: 600;">
          🧪 {{ $t('structureSearch.pageTitle') }}
        </h1>
        <p style="color: #606266;">{{ $t('structureSearch.pageSubtitle') }}</p>
      </div>
      
      <!-- 输入和3D可视化区域 -->
      <a-row :gutter="16" style="margin-bottom: 16px;">
        <!-- 左侧: 输入表单 -->
        <a-col :xs="24" :lg="10">
          <a-card style="border-radius: 8px; border: 1px solid #e4e7ed; height: 100%;">
            <a-form layout="vertical">
              <!-- 输入模式选择 -->
              <a-form-item :label="$t('structureSearch.inputModeLabel')">
                <a-radio-group v-model:value="inputMode" button-style="solid" size="large">
                  <a-radio-button value="database">
                    <database-outlined /> {{ $t('structureSearch.inputModeDatabase') }}
                  </a-radio-button>
                  <a-radio-button value="upload">
                    <upload-outlined /> {{ $t('structureSearch.inputModeUpload') }}
                  </a-radio-button>
                </a-radio-group>
              </a-form-item>
              
              <!-- 数据库选择模式 -->
              <a-form-item 
                v-if="inputMode === 'database'"
                :label="$t('structureSearch.selectProteinLabel')"
              >
                <a-select
                  v-model:value="selectedAccession"
                  show-search
                  :placeholder="$t('structureSearch.selectProteinPlaceholder')"
                  :filter-option="filterAccession"
                  :loading="loadingProteins"
                  size="large"
                  @change="handleProteinSelect"
                >
                  <a-select-option 
                    v-for="protein in proteinsWithPDB" 
                    :key="protein.accession" 
                    :value="protein.accession"
                  >
                    <div style="display: flex; justify-content: space-between;">
                      <span><strong>{{ protein.accession }}</strong></span>
                      <span style="color: #909399; font-size: 12px;">{{ protein.species }}</span>
                    </div>
                  </a-select-option>
                </a-select>
              </a-form-item>
              
              <!-- 文件上传模式 -->
              <a-form-item 
                v-if="inputMode === 'upload'"
                :label="$t('structureSearch.uploadFileLabel')"
              >
                <a-upload-dragger
                  v-model:file-list="fileList"
                  :before-upload="beforeUpload"
                  :max-count="1"
                  accept=".pdb"
                  @remove="handleRemove"
                  @change="handleFileChange"
                >
                  <p class="ant-upload-drag-icon">
                    <file-outlined style="color: #409eff; font-size: 48px;" />
                  </p>
                  <p class="ant-upload-text">{{ $t('structureSearch.uploadFileHint') }}</p>
                  <p class="ant-upload-hint">{{ $t('structureSearch.uploadFileSupport') }}</p>
                </a-upload-dragger>
              </a-form-item>
              
              <!-- 搜索参数 -->
              <a-form-item 
                :label="$t('structureSearch.tmScoreLabel')" 
                :help="$t('structureSearch.tmScoreHelp')"
              >
                <a-input-number
                  v-model:value="tmScoreThreshold"
                  :min="0"
                  :max="1"
                  :step="0.1"
                  style="width: 100%;"
                />
              </a-form-item>
              
              <a-form-item 
                :label="$t('structureSearch.maxResultsLabel')" 
                :help="$t('structureSearch.maxResultsHelp')"
              >
                <a-input-number
                  v-model:value="maxResults"
                  :min="10"
                  :max="500"
                  :step="10"
                  style="width: 100%;"
                />
              </a-form-item>
              
              <!-- 操作按钮 -->
              <a-form-item>
                <a-space>
                  <a-button 
                    type="primary" 
                    size="large" 
                    @click="searchStructure" 
                    :loading="searching"
                    :disabled="!canSearch"
                  >
                    <template #icon><search-outlined /></template>
                    {{ $t('structureSearch.searchButton') }}
                  </a-button>
                  <a-button size="large" @click="clearForm">
                    {{ $t('structureSearch.clearButton') }}
                  </a-button>
                </a-space>
              </a-form-item>
            </a-form>
          </a-card>
        </a-col>
        
        <!-- 右侧: 查询结构3D预览 -->
        <a-col :xs="24" :lg="14">
          <a-card 
            style="border-radius: 8px; border: 1px solid #e4e7ed; height: 100%;" 
            :body-style="{ padding: '16px', overflow: 'hidden' }"
          >
            <template #title>
              <span style="font-size: 16px; font-weight: 600;">
                🔍 查询结构预览
              </span>
            </template>
            
            <div v-if="queryStructureLoaded">
              <div style="position: relative; width: 100%; height: 500px; overflow: hidden;">
                <div 
                  id="query-viewer" 
                  style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: #263238; border-radius: 6px;"
                ></div>
              </div>
              <div style="margin-top: 12px;">
                <a-space wrap>
                  <a-button @click="setQueryStyle('cartoon')" size="small">Cartoon</a-button>
                  <a-button @click="setQueryStyle('stick')" size="small">Stick</a-button>
                  <a-button @click="setQueryStyle('sphere')" size="small">Sphere</a-button>
                  <a-button @click="resetQueryView" size="small" type="primary">
                    <redo-outlined /> 重置视图
                  </a-button>
                </a-space>
                <a-tag color="blue" style="margin-left: 8px;">
                  {{ queryIdentifier }}
                </a-tag>
              </div>
            </div>
            <a-empty 
              v-else 
              :description="inputMode === 'database' ? '请选择蛋白质查看结构' : '请上传PDB文件查看结构'" 
              style="padding: 120px 0;"
            />
          </a-card>
        </a-col>
      </a-row>
      
      <!-- 搜索结果 -->
      <a-card 
        v-if="searchResults" 
        style="border-radius: 8px; border: 1px solid #e4e7ed; margin-bottom: 16px;"
      >
        <template #title>
          <span style="font-size: 18px; color: #2c3e50; font-weight: 600;">
            {{ $t('structureSearch.resultsTitle') }}
            <a-tag v-if="searchResults.cached" color="blue" style="margin-left: 8px;">
              <template #icon><thunderbolt-outlined /></template>
              {{ $t('structureSearch.cached') }}
            </a-tag>
          </span>
        </template>
        
        <!-- 统计信息 -->
        <a-row :gutter="16" style="margin-bottom: 16px;">
          <a-col :span="6">
            <a-statistic 
              :title="$t('structureSearch.queryIdentifier')" 
              :value="searchResults.query_identifier"
            >
              <template #prefix>
                <experiment-outlined style="color: #1890ff;" />
              </template>
            </a-statistic>
          </a-col>
          <a-col :span="6">
            <a-statistic 
              :title="$t('structureSearch.totalHits')" 
              :value="searchResults.total_hits"
            >
              <template #prefix>
                <check-circle-outlined style="color: #52c41a;" />
              </template>
            </a-statistic>
          </a-col>
          <a-col :span="6">
            <a-statistic 
              v-if="searchResults.execution_time"
              :title="$t('structureSearch.executionTime')" 
              :value="searchResults.execution_time.toFixed(3)" 
              suffix="s"
            >
              <template #prefix>
                <clock-circle-outlined style="color: #faad14;" />
              </template>
            </a-statistic>
          </a-col>
          <a-col :span="6">
            <a-statistic 
              :title="$t('structureSearch.cacheStatus')" 
              :value="searchResults.cached ? $t('structureSearch.cacheHit') : $t('structureSearch.cacheMiss')"
            >
              <template #prefix>
                <database-outlined :style="{ color: searchResults.cached ? '#52c41a' : '#d9d9d9' }" />
              </template>
            </a-statistic>
          </a-col>
        </a-row>
        
        <!-- 结果表格 -->
        <a-table
          :dataSource="searchResults.results"
          :columns="columns"
          :pagination="{ pageSize: 10, showSizeChanger: true }"
          rowKey="accession"
          :scroll="{ x: 1200 }"
          :row-class-name="(record, index) => selectedResult?.accession === record.accession ? 'selected-row' : ''"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'accession'">
              <a-space>
                <a-button 
                  type="link" 
                  size="small" 
                  @click="loadResultStructure(record)"
                  :loading="loadingResultStructure === record.accession"
                >
                  <eye-outlined /> 查看
                </a-button>
                <router-link :to="`/protein/${record.id}`">
                  <a-typography-text copyable style="color: #1890ff;">
                    {{ record.accession }}
                  </a-typography-text>
                </router-link>
              </a-space>
            </template>
            
            <template v-else-if="column.key === 'species'">
              <a-tooltip :title="record.species">
                <span style="max-width: 200px; overflow: hidden; text-overflow: ellipsis; display: block;">
                  {{ record.species }}
                </span>
              </a-tooltip>
            </template>
            
            <template v-else-if="column.key === 'tm_score'">
              <a-progress
                :percent="record.tm_score * 100"
                :format="percent => `${(percent / 100).toFixed(3)}`"
                :strokeColor="getTMScoreColor(record.tm_score)"
                :showInfo="true"
                style="width: 150px;"
              />
            </template>
            
            <template v-else-if="column.key === 'probability'">
              <span :style="{ 
                color: record.probability > 0.95 ? '#52c41a' : record.probability > 0.8 ? '#1890ff' : '#606266',
                fontFamily: 'monospace'
              }">
                {{ record.probability.toFixed(4) }}
              </span>
            </template>
            
            <template v-else-if="column.key === 'rmsd'">
              <span style="font-family: monospace;">
                {{ record.rmsd }} Å
              </span>
            </template>
          </template>
        </a-table>
      </a-card>
      
      <!-- 结构对比区域 -->
      <a-card 
        v-if="selectedResult" 
        style="border-radius: 8px; border: 1px solid #e4e7ed; overflow: hidden;"
      >
        <template #title>
          <span style="font-size: 18px; font-weight: 600;">
            🔬 结构对比
          </span>
        </template>
        
        <a-row :gutter="16">
          <!-- 查询结构 -->
          <a-col :xs="24" :lg="12">
            <a-card size="small" :title="`查询: ${queryIdentifier}`" :body-style="{ padding: '12px', overflow: 'hidden' }">
              <div style="position: relative; width: 100%; height: 400px; overflow: hidden;">
                <div 
                  id="compare-query-viewer" 
                  style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: #263238; border-radius: 6px;"
                ></div>
              </div>
              <div style="margin-top: 8px; text-align: center;">
                <a-tag color="blue">TM-score: {{ selectedResult.tm_score.toFixed(3) }}</a-tag>
                <a-tag color="green">RMSD: {{ selectedResult.rmsd }} Å</a-tag>
              </div>
            </a-card>
          </a-col>
          
          <!-- 匹配结构 -->
          <a-col :xs="24" :lg="12">
            <a-card size="small" :title="`匹配: ${selectedResult.accession}`" :body-style="{ padding: '12px', overflow: 'hidden' }">
              <div style="position: relative; width: 100%; height: 400px; overflow: hidden;">
                <div 
                  id="compare-result-viewer" 
                  style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: #263238; border-radius: 6px;"
                ></div>
              </div>
              <div style="margin-top: 8px; text-align: center;">
                <a-tag color="purple">{{ selectedResult.species }}</a-tag>
                <a-tag>{{ selectedResult.type }}</a-tag>
              </div>
            </a-card>
          </a-col>
        </a-row>
        
        <div style="text-align: center; margin-top: 16px;">
          <a-space size="large">
            <a-button type="primary" @click="syncViews" size="large">
              <sync-outlined /> 同步视图
            </a-button>
            <a-button 
              :type="realtimeSync ? 'primary' : 'default'" 
              @click="toggleRealtimeSync" 
              size="large"
              :danger="realtimeSync"
            >
              <sync-outlined :spin="realtimeSync" /> 
              {{ realtimeSync ? '实时同步: 开启' : '实时同步: 关闭' }}
            </a-button>
            <a-button @click="closeComparison" size="large">
              关闭对比
            </a-button>
          </a-space>
        </div>
      </a-card>
    </a-layout-content>
  </a-layout>
</template>

<script setup>
import { ref, computed, onMounted, nextTick, onBeforeUnmount, onActivated, onDeactivated } from 'vue'
import { useI18n } from 'vue-i18n'
import { 
  SearchOutlined, 
  DatabaseOutlined,
  UploadOutlined,
  ThunderboltOutlined,
  ExperimentOutlined,
  CheckCircleOutlined,
  ClockCircleOutlined,
  FileOutlined,
  EyeOutlined,
  RedoOutlined,
  SyncOutlined
} from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import axios from 'axios'
import config from '../config/env'
import NavBar from '../components/NavBar.vue'

const { t } = useI18n()

// 输入模式
const inputMode = ref('database')
const selectedAccession = ref(undefined)
const fileList = ref([])
const queryIdentifier = ref('')

// 搜索参数
const tmScoreThreshold = ref(0.5)
const maxResults = ref(100)

// 状态
const searching = ref(false)
const searchResults = ref(null)
const loadingProteins = ref(false)
const proteinsWithPDB = ref([])
const selectedResult = ref(null)
const loadingResultStructure = ref(null)

// 3D查看器
let queryViewer = null
let compareQueryViewer = null
let compareResultViewer = null
const queryStructureLoaded = ref(false)
const queryPdbData = ref(null)

// 实时同步控制
const realtimeSync = ref(false)
let syncInterval = null

// 是否可以搜索
const canSearch = computed(() => {
  if (inputMode.value === 'database') {
    return selectedAccession.value !== undefined
  } else {
    return fileList.value.length > 0
  }
})

// 表格列定义
const columns = computed(() => [
  { 
    title: t('structureSearch.table.accession'), 
    dataIndex: 'accession', 
    key: 'accession', 
    width: 200, 
    fixed: 'left' 
  },
  { 
    title: t('structureSearch.table.species'), 
    dataIndex: 'species', 
    key: 'species', 
    width: 200, 
    ellipsis: true 
  },
  { 
    title: t('structureSearch.table.type'), 
    dataIndex: 'type', 
    key: 'type', 
    width: 120 
  },
  { 
    title: t('structureSearch.table.tmScore'), 
    dataIndex: 'tm_score', 
    key: 'tm_score', 
    width: 180,
    sorter: (a, b) => a.tm_score - b.tm_score,
    defaultSortOrder: 'descend'
  },
  { 
    title: t('structureSearch.table.probability'), 
    dataIndex: 'probability', 
    key: 'probability', 
    width: 100,
    sorter: (a, b) => a.probability - b.probability
  },
  { 
    title: t('structureSearch.table.rmsd'), 
    dataIndex: 'rmsd', 
    key: 'rmsd', 
    width: 100,
    sorter: (a, b) => a.rmsd - b.rmsd
  },
  { 
    title: t('structureSearch.table.alignmentLength'), 
    dataIndex: 'alignment_length', 
    key: 'alignment_length', 
    width: 100 
  }
])

// 加载3Dmol.js
const load3DMol = () => {
  return new Promise((resolve, reject) => {
    if (window.$3Dmol) {
      resolve()
      return
    }
    
    const script = document.createElement('script')
    script.src = 'https://3Dmol.csb.pitt.edu/build/3Dmol-min.js'
    script.onload = () => resolve()
    script.onerror = () => reject(new Error('Failed to load 3Dmol'))
    document.head.appendChild(script)
  })
}

// 加载有PDB文件的蛋白质列表
const loadProteinsWithPDB = async () => {
  loadingProteins.value = true
  try {
    // 使用搜索API获取所有有PDB文件的蛋白质
    const response = await axios.get(`${config.API_BASE_URL}/api/search/`, {
      params: { 
        q: '',
        page: 1,
        page_size: 1000
      }
    })
    
    proteinsWithPDB.value = response.data.proteins
      .filter(p => p.has_pdb)
      .map(p => ({
        id: p.id,
        accession: p.accession,
        species: p.species
      }))
  } catch (error) {
    console.error('Failed to load proteins:', error)
    message.error('加载蛋白质列表失败')
  } finally {
    loadingProteins.value = false
  }
}

// 处理蛋白质选择
const handleProteinSelect = async (accession) => {
  queryIdentifier.value = accession
  await loadQueryStructureFromDB(accession)
}

// 从数据库加载查询结构
const loadQueryStructureFromDB = async (accession) => {
  try {
    await load3DMol()
    
    // 从已加载的蛋白质列表中查找ID
    const protein = proteinsWithPDB.value.find(p => p.accession === accession)
    
    if (!protein) {
      throw new Error('未找到该蛋白质')
    }
    
    // 使用正确的PDB API路径
    const pdbResponse = await axios.get(`${config.API_BASE_URL}/pdb/${protein.id}`)
    queryPdbData.value = pdbResponse.data.pdb_content
    
    await nextTick()
    
    const element = document.getElementById('query-viewer')
    if (!element) return
    
    if (queryViewer) {
      queryViewer.clear()
    }
    
    queryViewer = window.$3Dmol.createViewer(element, {
      backgroundColor: '#263238'
    })
    
    queryViewer.addModel(queryPdbData.value, 'pdb')
    queryViewer.setStyle({}, { cartoon: { color: 'spectrum' } })
    queryViewer.zoomTo()
    queryViewer.render()
    
    queryStructureLoaded.value = true
    message.success('查询结构已加载')
  } catch (error) {
    console.error('Failed to load query structure:', error)
    message.error('加载查询结构失败')
  }
}

// 处理文件变化
const handleFileChange = async ({ fileList: newFileList }) => {
  // 如果文件被清空
  if (newFileList.length === 0) {
    queryStructureLoaded.value = false
    if (queryViewer) {
      queryViewer.clear()
    }
    return
  }
  
  if (newFileList.length > 0 && newFileList[0].originFileObj) {
    const file = newFileList[0].originFileObj
    queryIdentifier.value = file.name
    
    try {
      const text = await file.text()
      queryPdbData.value = text
      
      await load3DMol()
      
      // 先设置为true,确保DOM元素存在
      queryStructureLoaded.value = true
      
      // 等待DOM更新
      await nextTick()
      
      const element = document.getElementById('query-viewer')
      if (!element) {
        console.error('query-viewer element not found')
        return
      }
      
      if (queryViewer) {
        queryViewer.clear()
      }
      
      queryViewer = window.$3Dmol.createViewer(element, {
        backgroundColor: '#263238'
      })
      
      queryViewer.addModel(text, 'pdb')
      queryViewer.setStyle({}, { cartoon: { color: 'spectrum' } })
      queryViewer.zoomTo()
      queryViewer.render()
      
      message.success('PDB文件已加载')
    } catch (error) {
      console.error('Failed to load PDB file:', error)
      message.error('加载PDB文件失败: ' + error.message)
      queryStructureLoaded.value = false
    }
  }
}

// 过滤Accession
const filterAccession = (input, option) => {
  const accession = option.value.toLowerCase()
  const children = option.children
  const species = children && children[0] && children[0].children && children[0].children[1] 
    ? children[0].children[1].children.toLowerCase() 
    : ''
  return accession.includes(input.toLowerCase()) || species.includes(input.toLowerCase())
}

// 文件上传前验证
const beforeUpload = (file) => {
  const isPDB = file.name.endsWith('.pdb')
  if (!isPDB) {
    message.error(t('structureSearch.fileError'))
    return false
  }
  
  const isLt10M = file.size / 1024 / 1024 < 10
  if (!isLt10M) {
    message.error(t('structureSearch.fileTooLarge'))
    return false
  }
  
  return false
}

// 移除文件
const handleRemove = () => {
  fileList.value = []
  queryStructureLoaded.value = false
  if (queryViewer) {
    queryViewer.clear()
  }
}

// 执行搜索
const searchStructure = async () => {
  if (!canSearch.value) {
    message.error(t('structureSearch.noInput'))
    return
  }
  
  searching.value = true
  searchResults.value = null
  selectedResult.value = null
  
  try {
    const formData = new FormData()
    
    if (inputMode.value === 'database') {
      formData.append('query_accession', selectedAccession.value)
    } else {
      formData.append('pdb_file', fileList.value[0].originFileObj)
    }
    
    formData.append('tm_score_threshold', tmScoreThreshold.value)
    formData.append('max_results', maxResults.value)
    
    const response = await axios.post(
      `${config.API_BASE_URL}/api/search/structure/`,
      formData,
      {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }
    )
    
    searchResults.value = response.data
    
    if (response.data.total_hits === 0) {
      message.warning(t('structureSearch.noResults'))
    } else {
      // 显示搜索结果消息
      let msg = t('structureSearch.searchSuccess', { count: response.data.total_hits })
      
      // 检查是否缓存命中
      if (response.data.cached === true) {
        msg += ` (${t('structureSearch.cached')})`
      }
      
      // 添加执行时间
      if (response.data.execution_time != null) {
        msg += ` - ${response.data.execution_time.toFixed(3)}s`
      }
      
      message.success(msg)
      
      // 控制台输出调试信息
      console.log('[结构搜索] 缓存状态:', response.data.cached, '执行时间:', response.data.execution_time)
    }
  } catch (error) {
    const detail = error.response?.data?.detail || error.message
    message.error(t('structureSearch.searchFailed') + ': ' + detail)
    console.error('Search error:', error)
  } finally {
    searching.value = false
  }
}

// 加载结果结构
const loadResultStructure = async (result) => {
  loadingResultStructure.value = result.accession
  selectedResult.value = result
  
  try {
    await load3DMol()
    
    // 使用正确的PDB API路径
    const pdbResponse = await axios.get(`${config.API_BASE_URL}/pdb/${result.id}`)
    const resultPdbData = pdbResponse.data.pdb_content
    
    await nextTick()
    
    // 加载查询结构到对比视图
    const queryElement = document.getElementById('compare-query-viewer')
    if (queryElement) {
      if (compareQueryViewer) {
        compareQueryViewer.clear()
      }
      
      compareQueryViewer = window.$3Dmol.createViewer(queryElement, {
        backgroundColor: '#263238'
      })
      
      compareQueryViewer.addModel(queryPdbData.value, 'pdb')
      compareQueryViewer.setStyle({}, { cartoon: { color: 'lightblue' } })
      compareQueryViewer.zoomTo()
      compareQueryViewer.render()
    }
    
    // 加载结果结构到对比视图
    const resultElement = document.getElementById('compare-result-viewer')
    if (resultElement) {
      if (compareResultViewer) {
        compareResultViewer.clear()
      }
      
      compareResultViewer = window.$3Dmol.createViewer(resultElement, {
        backgroundColor: '#263238'
      })
      
      compareResultViewer.addModel(resultPdbData, 'pdb')
      compareResultViewer.setStyle({}, { cartoon: { color: 'lightcoral' } })
      compareResultViewer.zoomTo()
      compareResultViewer.render()
    }
    
    message.success('结构对比已加载')
  } catch (error) {
    console.error('Failed to load result structure:', error)
    message.error('加载结构失败')
  } finally {
    loadingResultStructure.value = null
  }
}

// 设置查询结构样式
const setQueryStyle = (style) => {
  if (!queryViewer) return
  
  queryViewer.setStyle({}, {})
  
  switch (style) {
    case 'cartoon':
      queryViewer.setStyle({}, { cartoon: { color: 'spectrum' } })
      break
    case 'stick':
      queryViewer.setStyle({}, { stick: {} })
      break
    case 'sphere':
      queryViewer.setStyle({}, { sphere: {} })
      break
  }
  
  queryViewer.render()
}

// 重置查询视图
const resetQueryView = () => {
  if (!queryViewer) return
  queryViewer.zoomTo()
  queryViewer.render()
}

// 同步对比视图 (左→右)
const syncViews = () => {
  if (compareQueryViewer && compareResultViewer) {
    const view = compareQueryViewer.getView()
    compareResultViewer.setView(view)
    compareResultViewer.render()
    message.success('视图已同步')
  }
}

// 切换实时同步
const toggleRealtimeSync = () => {
  realtimeSync.value = !realtimeSync.value
  
  if (realtimeSync.value) {
    // 启动实时同步
    startRealtimeSync()
    message.success('已启用实时同步')
  } else {
    // 停止实时同步
    stopRealtimeSync()
    message.info('已禁用实时同步')
  }
}

// 启动实时同步
const startRealtimeSync = () => {
  if (syncInterval) {
    clearInterval(syncInterval)
  }
  
  let lastQueryView = null
  let lastResultView = null
  
  syncInterval = setInterval(() => {
    if (!compareQueryViewer || !compareResultViewer) return
    
    try {
      const queryView = compareQueryViewer.getView()
      const resultView = compareResultViewer.getView()
      
      // 检查左侧视图是否变化
      if (JSON.stringify(queryView) !== JSON.stringify(lastQueryView)) {
        compareResultViewer.setView(queryView)
        compareResultViewer.render()
        lastQueryView = queryView
        lastResultView = queryView
      }
      // 检查右侧视图是否变化
      else if (JSON.stringify(resultView) !== JSON.stringify(lastResultView)) {
        compareQueryViewer.setView(resultView)
        compareQueryViewer.render()
        lastResultView = resultView
        lastQueryView = resultView
      }
    } catch (error) {
      // 忽略同步错误
    }
  }, 10) // 每100ms检查一次
}

// 停止实时同步
const stopRealtimeSync = () => {
  if (syncInterval) {
    clearInterval(syncInterval)
    syncInterval = null
  }
}

// 关闭结构对比
const closeComparison = () => {
  selectedResult.value = null
  realtimeSync.value = false
  stopRealtimeSync()
}

// 清空表单
const clearForm = () => {
  selectedAccession.value = undefined
  fileList.value = []
  searchResults.value = null
  selectedResult.value = null
  queryStructureLoaded.value = false
  queryPdbData.value = null
  
  if (queryViewer) {
    queryViewer.clear()
  }
  
  message.info(t('structureSearch.cleared'))
}

// TM-score颜色映射
const getTMScoreColor = (tmScore) => {
  if (tmScore >= 0.8) return '#52c41a'
  if (tmScore >= 0.6) return '#1890ff'
  if (tmScore >= 0.4) return '#faad14'
  return '#f5222d'
}

// 组件状态保存和恢复
// 保存的状态
let savedState = {
  inputMode: null,
  selectedAccession: null,
  fileList: null,
  tmScoreThreshold: null,
  maxResults: null,
  searchResults: null,
  queryIdentifier: null,
  queryStructureLoaded: null,
  queryPdbData: null
}

// 保存当前状态
const saveState = () => {
  savedState = {
    inputMode: inputMode.value,
    selectedAccession: selectedAccession.value,
    fileList: fileList.value,
    tmScoreThreshold: tmScoreThreshold.value,
    maxResults: maxResults.value,
    searchResults: searchResults.value,
    queryIdentifier: queryIdentifier.value,
    queryStructureLoaded: queryStructureLoaded.value,
    queryPdbData: queryPdbData.value
  }
  console.log('[状态保存] 已保存搜索状态')
}

// 恢复状态
const restoreState = async () => {
  if (savedState.inputMode) {
    inputMode.value = savedState.inputMode
    selectedAccession.value = savedState.selectedAccession
    fileList.value = savedState.fileList || []
    tmScoreThreshold.value = savedState.tmScoreThreshold || 0.5
    maxResults.value = savedState.maxResults || 100
    searchResults.value = savedState.searchResults
    queryIdentifier.value = savedState.queryIdentifier
    queryPdbData.value = savedState.queryPdbData
    
    // 恢复3D查看器
    if (savedState.queryStructureLoaded && savedState.queryPdbData) {
      queryStructureLoaded.value = true
      await nextTick()
      
      await load3DMol()
      const element = document.getElementById('query-viewer')
      if (element && queryPdbData.value) {
        if (queryViewer) {
          queryViewer.clear()
        }
        
        queryViewer = window.$3Dmol.createViewer(element, {
          backgroundColor: '#263238'
        })
        
        queryViewer.addModel(queryPdbData.value, 'pdb')
        queryViewer.setStyle({}, { cartoon: { color: 'spectrum' } })
        queryViewer.zoomTo()
        queryViewer.render()
      }
    }
    
    console.log('[状态恢复] 已恢复搜索状态')
  }
}

// 组件卸载前保存状态
onBeforeUnmount(() => {
  saveState()
  stopRealtimeSync()
})

// keep-alive激活时恢复状态
onActivated(() => {
  restoreState()
})

// keep-alive停用时保存状态
onDeactivated(() => {
  saveState()
})

// 挂载时加载蛋白质列表
onMounted(async () => {
  await loadProteinsWithPDB()
  await load3DMol()
  
  // 尝试恢复状态
  await restoreState()
})
</script>

<style scoped>
:deep(.ant-btn-primary) {
  background: #409eff;
  border-color: #409eff;
}

:deep(.ant-btn-primary:hover) {
  background: #66b1ff;
  border-color: #66b1ff;
}

:deep(.ant-radio-button-wrapper-checked) {
  background: #409eff !important;
  border-color: #409eff !important;
}

:deep(.ant-statistic-title) {
  color: #606266;
  font-size: 14px;
}

:deep(.ant-statistic-content) {
  color: #2c3e50;
  font-weight: 600;
}

:deep(.ant-table-thead > tr > th) {
  background: #fafafa;
  color: #2c3e50;
  font-weight: 600;
}

:deep(.ant-progress-text) {
  font-size: 12px;
}

:deep(.ant-card-head) {
  border-bottom: 1px solid #e4e7ed;
}

:deep(.ant-upload-drag) {
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  background: #fafafa;
}

:deep(.ant-upload-drag:hover) {
  border-color: #409eff;
}

:deep(.selected-row) {
  background-color: #e6f7ff !important;
}

:deep(.selected-row:hover) {
  background-color: #bae7ff !important;
}

/* 强制限制3Dmol查看器不溢出 */
#query-viewer,
#compare-query-viewer,
#compare-result-viewer {
  max-width: 100%;
  max-height: 100%;
}

/* 确保3Dmol的canvas不溢出 */
#query-viewer canvas,
#compare-query-viewer canvas,
#compare-result-viewer canvas {
  max-width: 100% !important;
  max-height: 100% !important;
  position: absolute !important;
  top: 0 !important;
  left: 0 !important;
}

/* 确保卡片body不溢出 */
:deep(.ant-card-body) {
  overflow: hidden !important;
}
</style>

